<?php
/**
 * XmlTranslator-Klasse
 *
 * XML im Format
 *	<?xml version="1.0" encoding="ISO-8859-1"?>
 *		<root>
 *			<language id="DE_DE">
 *				<element id="TITLE">Ueberschrift</element>
 *				<element id="DESCRIPTION">Hallo Welt</element>
 *			</language>
 *			<language id="EN_EN">
 *				<element id="TITLE">Headline</element>
 *				<element id="DESCRIPTION">Hello world</element>
 *			</language>
 *		</root>
 *
 * @author		Joachim Ruf
 * @copyright	Copyright (c) 2003-2010 Loresoft Software (http://www.loresoft.de)
 * @license		http://yapary.loresoft.de/lizenzbedingungen     New BSD License
 *
 * */


class Yapary_Translation_XmlTranslator
{
	private $oSimpleXmlElement	= NULL;
	private $languageCode		= NULL;


	/**
	 * @param $_xml				: XML-Code mit Uebersetzungen
	 * @param $_languageCode	: Sprachkennung im Format de_DE welche als default verwendet werden soll
	 * */
	function __construct ($_xml, $_languageCode) {
		$this->oSimpleXmlElement	= simplexml_load_string($_xml);
		$this->languageCode			= $_languageCode;

		if (!is_object($this->oSimpleXmlElement)) {
			throw new Exception('Unable to load XML');
		}
	}


	/**
	* Gibt eine definierte Uebersetzung aus
	* @param string $translationId	: Id der Uebersetzung
	* @param sting $languageCode	: (optional) LanguageCode der auszugebenden Uebersetzung.
	* 								  Wenn nicht weiter angegeben, wir die standarduebersetzung verwendet
	* @return string|NULL
	*/
	function get($translationID, array $arrVarReplace = array(), $languageCode = NULL) {
		$languageCode = ($languageCode == NULL) ? $this->languageCode : $languageCode;

		$xPath		= "/root/language[@id=\"$languageCode\"]/element[@id=\"$translationID\"]";
		$arrResult	= $this->oSimpleXmlElement->xpath($xPath);

		if (count($arrResult) == 0) {
			trigger_error('Unable to find translation '.$translationID, E_USER_WARNING);
		}

		if (count($arrVarReplace)) {
			$result = $arrResult[0];
			foreach ($arrVarReplace as $key => $val) {
				$result = str_replace('{'.$key.'}', $val, $result);
			}
			return $result;
		}

		return $arrResult[0];
	}


	function getList ($languageCode = NULL) {
		$languageCode = ($languageCode == NULL) ? $this->languageCode : $languageCode;

		$xPath		= "/root/language[@id=\"$languageCode\"]";
		$arr		= $this->oSimpleXmlElement->xpath($xPath);

		$xPathElId	= "/root/language[@id=\"$languageCode\"]/element";
		$arrElId	= $this->oSimpleXmlElement->xpath($xPathElId);


		if (count($arr[0]->children())) {
			$i = 0;
			/* @var $val SimpleXMLElement */
			foreach ($arr[0]->children() as $key => $val) {
				/* @var $arrElId SimpleXMLElement */
				$elId = $arrElId[$i++]->attributes()->__toString();
				$val->__toString();

				$arrResult[$elId] = $val->__toString();
			}
		}

		return $arrResult;
	}

}


?>